package com.otaliastudios.cameraview.internal;

import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;

import androidx.exifinterface.media.ExifInterface;

import com.ecarx.camera.utils.LogUtils;
import com.ecarx.camera.utils.Utils;

import java.io.IOException;

/**
 * Super basic exif utilities.
 */
public class ExifHelper {

    /**
     * Maps an {@link ExifInterface} orientation value
     * to the actual degrees.
     */
    public static int getOrientation(int exifOrientation) {
        int orientation;
        switch (exifOrientation) {
            case ExifInterface.ORIENTATION_NORMAL:
            case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                orientation = 0; break;

            case ExifInterface.ORIENTATION_ROTATE_180:
            case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                orientation = 180; break;

            case ExifInterface.ORIENTATION_ROTATE_90:
            case ExifInterface.ORIENTATION_TRANSPOSE:
                orientation = 90; break;

            case ExifInterface.ORIENTATION_ROTATE_270:
            case ExifInterface.ORIENTATION_TRANSVERSE:
                orientation = 270; break;

            default: orientation = 0;
        }
        return orientation;
    }

    /**
     * Maps a degree value to {@link ExifInterface} constant.
     */
    public static int getExifOrientation(int orientation) {
        switch ((orientation + 360) % 360) {
            case 0: return ExifInterface.ORIENTATION_NORMAL;
            case 90: return ExifInterface.ORIENTATION_ROTATE_90;
            case 180: return ExifInterface.ORIENTATION_ROTATE_180;
            case 270: return ExifInterface.ORIENTATION_ROTATE_270;
            default: throw new IllegalArgumentException("Invalid orientation: " + orientation);
        }
    }


    public static void setExifLocation(Uri uri, double latitude, double longitude){
        // 通过 ContentResolver 获取图片的实际文件路径
        String filePath = getRealPathFromURI(uri);
        if(!TextUtils.isEmpty(filePath)){
            LogUtils.i("ExifHelper", " onPictureTaken:", "setExifLocation=" + filePath, latitude, longitude);
            writeLocationToPhoto1(filePath, latitude, longitude);
        }
    }

    public static void readLocation1(Uri uri){
        String photoPath = getRealPathFromURI(uri);
        if(TextUtils.isEmpty(photoPath)){
            return;
        }
        try {
            // 获取 ExifInterface 对象
            ExifInterface exif = new ExifInterface(photoPath);

            // 读取经度信息
            String latitude = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
            if (latitude != null) {
                float latitudeValue = convertToDegree(latitude);
                // 处理经度值（latitudeValue）
                LogUtils.i("ExifHelper 获取经纬度latitudeValue="+ latitudeValue);
            }

            // 读取纬度信息
            String longitude = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
            if (longitude != null) {
                float longitudeValue = convertToDegree(longitude);
                // 处理纬度值（longitudeValue）
                LogUtils.i("ExifHelper 获取经纬度longitudeValue="+ longitudeValue);
            }

            // 其他 Exif 信息的读取，可以根据需要继续添加
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void readLocation2(Uri uri){
        String photoPath = getRealPathFromURI(uri);
        if(TextUtils.isEmpty(photoPath)){
            return;
        }
        try {
            ExifInterface exif = new ExifInterface(photoPath);
            double[] latLon = exif.getLatLong();
            if(latLon != null){
                LogUtils.i("ExifHelper 获取经纬度", latLon[0] , latLon[1]);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static float convertToDegree(String stringDMS) {
        float result = 0;
        String[] DMS = stringDMS.split(",", 3);
        for (int i = 0; i < DMS.length; i++) {
            String[] stringD = DMS[i].split("/", 2);
            double value = Double.parseDouble(stringD[0]) / Double.parseDouble(stringD[1]);
            switch (i) {
                case 0:
                    result += value;
                    break;
                case 1:
                    result += value / 60;
                    break;
                case 2:
                    result += value / 3600;
                    break;
            }
        }
        return result;
    }

    private static String getRealPathFromURI(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = Utils.getApp().getContentResolver().query(uri, projection, null, null, null);
        if(cursor == null){
            return "";
        }
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String filePath = cursor.getString(column_index);
        cursor.close();
        return filePath;
    }

    public static void writeLocationToPhoto1(String photoPath, double latitude, double longitude) {
        try {
            ExifInterface exif = new ExifInterface(photoPath);
            exif.setLatLong(latitude, longitude);
            exif.saveAttributes();
        } catch (IOException e) {
            LogUtils.w("ExifHelper", " 写入经纬度信息失败，但不影响图片生成", e.getMessage());
        }
    }

    public static void writeLocationToPhoto2(String photoPath, double latitude, double longitude) {
        try {
            ExifInterface exif = new ExifInterface(photoPath);
            exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE, convert(latitude));
            exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, convert(longitude));
            exif.saveAttributes();
        } catch (IOException e) {
            LogUtils.w("ExifHelper", " 写入经纬度信息失败，但不影响图片生成", e.getMessage());
        }
    }

    // 将经纬度信息从度转换为度分秒格式
    private static String convert(double input) {
        int deg = (int) input;
        input = (input - deg) * 60;
        int min = (int) input;
        input = (input - min) * 60;
        int sec = (int) (input * 1000);
        return deg + "/1," + min + "/1," + sec + "/1000";
    }
}

